package com.zy.common.core.interceptor;

import com.zy.common.core.R;
import com.zy.common.core.enums.ErrorEnums;
import com.zy.common.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常信息统一拦截
 *
 * @author zy
 * @since 2023/3/13 16:01
 */

@Slf4j
@RestControllerAdvice
public class ErrorHandler implements HandlerInterceptor {

    @ExceptionHandler(value = Exception.class)
    R handlerException(Exception e, HttpServletRequest request) {
        if (e instanceof BizException) {
            e.printStackTrace();
            return R.fail(((BizException) e).getCode(), e.getMessage());

        }
        log.error(e.getMessage());
        return R.fail(ErrorEnums.SYSTEM_ERROR);
    }

}
